import {UploadFileObj} from "@/utils/uploadFile";
import guid from "@/utils/guid";
import {isArr} from "@/utils/arrayUtil";

const listPageMixins = {
  data() {
    return {
      pageQueryParam: {
        pageNum: 1,
        pageSize: 10,
      },
      orderByParam: {
        orderByColumn: null,
        isAsc: null,
      },
      loading: false,
      dataList: [],
      total: 0,
      tableQueryParams: {},
      open: false,
      title: '',
      form: {},
      uid: `f${guid()}`,
      // 选中数组
      ids: [],
      multiple: true,
      infoData: {},
      infoOpen: false,
      reloadTable: true,
    }
  },
  computed: {
    fileList() {
      let res = this.$store.state.temporaryFile.temporaryFileList
      return isArr(res) && res.some(item => item.uid == this.uid) ? res.find(item => item.uid == this.uid).fileList : []
    }
  },
  methods: {
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      if (column.order != null && column.order !== '') {
        this.orderByParam.orderByColumn = column.prop;
        if (column.order.startsWith('asc')) {
          this.orderByParam.isAsc = 'asc'
        }
        if (column.order.startsWith('desc')) {
          this.orderByParam.isAsc = 'desc'
        }
      } else {
        this.orderByParam.orderByColumn = null
        this.orderByParam.isAsc = null;
      }
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      let owner = this
      this.$modal.confirm('是否确认删除当前数据项？').then(function () {
        return owner.deleteFun({ids: ids.toString()});
      }).then(() => {
        owner.getList();
        owner.$modal.msgSuccess("删除成功");
        owner.submitChange()
      }).catch(() => {
      });
    },
    // 提交事件
    submitChange() {
      this.$emit('change')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let {uid, fileFiled} = this
      let owner = this
      if (fileFiled != null && fileFiled !== '') {
        this.$store.commit('temporaryFile/REMOVE_ALL_FILE', this.uid)
      }
      this.getInfoData(row.id).then(data => {
        if (isArr(data[fileFiled])) {
          owner.$store.dispatch('temporaryFile/addDocList', {uid: this.uid, fileList: data[fileFiled]})
        }
        this.form = data;
        this.open = true;
        this.title = `修改${this.modelName}`;
      });
    },
    /** 详情 */
    showInfo(row) {
      let owner = this
      this.startLoading('正在加载....')
      this.getInfoData(row.id).then(data => {
        owner.infoData = data
        owner.infoOpen = true
      }).finally(() => {
        owner.endLoading()
      })
    },
    /** 获取一条数据的详情 */
    getInfoData(id) {
      return new Promise((resolve, reject) => {
        this.getInfoFun({id}).then(response => {
          resolve(response.data)
        }).catch(() => {
          reject()
        });
      })
    },
    submitData() {
      let owner = this
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.startLoading('正在加载....')
          if (this.form.id != null) {
            this.updateFun(this.form).then(response => {
              owner.$modal.msgSuccess('更新成功')
              owner.open = false
              owner.getList()
            }).finally(() => {
              owner.infoOpen = false
              owner.submitChange()
              owner.endLoading()
              if (owner.endFun && typeof owner.endFun == 'function'){
                owner.endFun()
              }
            });
          } else {
            this.addFun(this.form).then(response => {
              owner.$modal.msgSuccess('新增成功')
              owner.open = false
              owner.getList()
            }).finally(() => {
              owner.infoOpen = false
              owner.submitChange()
              owner.endLoading()
              if (owner.endFun && typeof owner.endFun == 'function'){
                owner.endFun()
              }
            });
          }
        }
      })
    },
    /** 上传文件 */
    upload() {
      let uploadObj = UploadFileObj.getInstance();
      uploadObj.uploadFile('temporaryFile/addDoc', {uid: this.uid})
    },
    //删除附件列表中附件回调函数
    delFile(item) {
      let owner = this
      let {uid} = this
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        let {fileId, fileName,} = item
        owner.$store.dispatch("temporaryFile/removeProjectDoc", {uid, fileId, fileName,},).then(() => {
          owner.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.tableQueryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 表单重置  */
    reset() {
      this.form = _.cloneDeep(this.baseForm);
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      let {modelName} = this
      this.reset();
      this.$store.commit('temporaryFile/REMOVE_ALL_FILE', this.uid)
      this.open = true;
      this.title = `添加${modelName}`;
    },
    getList() {
      let owner = this
      if (this.getListFun == null || typeof this.getListFun !== 'function') return;
      let {otherQueryParam, orderByParam} = this;
      let queryParam = otherQueryParam != null ? {...otherQueryParam, ...this.tableQueryParams} : this.tableQueryParams;
      queryParam = {...queryParam, ...orderByParam}
      if (this.preposition != null && typeof this.preposition == 'function') {
        if (!this.preposition(queryParam)) {
          return;
        }
      }
      owner.startLoading('正在加载....')
      this.getListFun(queryParam).then(response => {
          let rows = response?.rows || response?.data
          owner.dataList = owner.changeRowData && typeof owner.changeRowData === 'function' ? owner.changeRowData(rows) : rows;
          owner.total = response.total;
          owner.reloadTable = false
          setTimeout(() => {
            owner.reloadTable = true
            owner.endLoading()
          }, 2)
        }
      ).catch((e) => {
        owner.endLoading()
      }).finally(() => {
      });
    },
  },
  created() {
    let {pageQueryParam, queryParams} = this
    queryParams = queryParams || {}
    pageQueryParam = pageQueryParam || {}
    this.tableQueryParams = {...pageQueryParam, ...queryParams};
    if (this.getListFun && typeof this.getListFun == 'function') {
      this.getList()
    }
  }
}

export {listPageMixins}
